package main

import (
	"fmt"
	"os"
	"os/signal"
	"storj.io/uplink/p2p"
	"sync"
	"syscall"
	"time"
)

const licenKey="AQAAAFN1pQ7o+sRwhzzbSPpFkOaDwBToCSQ14FSSKRidnONzdeKaBHSUhS/rHJECkbmhaXGnKN4lMqjQP9nz6SFOclVRQTLYbdAPbLdsJO7/FiqfOhgp3CQ1Oaqdz5alo0DUr4fAhPTdE+JA/M+5opVrVLGTB1RcWuIXEwJ2QHeO71Ycalu1/RKCCIu0GWWPbvgyTc5Uzx06eIKfntwbE55dunQb"
const maxConn=30

type Task struct {
	finish bool
	infos []*p2p.TunnelInfo
	wg *sync.WaitGroup
	fileName string
	speed int
}

func NewTask( wg *sync.WaitGroup, file string, speed int)(*Task)  {
	t1 :=Task{
		wg: wg,
		fileName:file,
		speed: speed,
	}
	wg.Add(1)
	t1.infos = make([]*p2p.TunnelInfo,0)
	return &t1
}

func (t*Task)DoTask(agent *p2p.Agent)  {
	//连接，返回一组端口号
	agent.BlindTunnel(t.infos)

	go agent.Service(t.infos,&t.finish,t.wg) //不断监听端口状态

	//send data
	time.Sleep(time.Second*1)
	SendFile(t.infos[0].LocalPort,t.fileName,t.speed)
	t.finish = true
}


func main()  {
	fmt.Println("p2p test")
	if len(os.Args) < 2{
		fmt.Println("useage: tcpclien file")
		return
	}

	sigs := make(chan  os.Signal,1)
	signal.Notify(sigs,syscall.SIGINT, syscall.SIGTERM)
	wg := &sync.WaitGroup{}


	agent := p2p.NewAgent()
	if !agent.AgentInit(licenKey,maxConn){
		return
	}
	defer agent.Close()


	t1 := NewTask(wg,os.Args[1],1024)
	t1.infos = append(t1.infos, &p2p.TunnelInfo{
		Uid: "RN65AYDYHYRPJZDZ111A",
		LocalPort: 13001,
		RemotePort: 13000,
		Tag: "task1",
	})


	//t2 := NewTask(wg,os.Args[1],500)
	//t2.infos = append(t2.infos, &p2p.TunnelInfo{
	//	Uid: "RN65AYDYHYRPJZDZ111A",
	//	LocalPort: 13000,
	//	RemotePort: 13000,
	//	Tag: "task2",
	//})
	//go t2.DoTask(agent)
	go t1.DoTask(agent)


	wg.Wait()

}

